import threading
import time

# 创建一个线程锁
lock = threading.Lock()

# 共享资源
shared_resource = 0


def update_shared_resource():
    global shared_resource

    # 获取线程锁
    lock.acquire()

    try:
        # 在这里执行需要同步的操作
        shared_resource += 1
        print(f"Thread {threading.current_thread().name} updated shared resource: {shared_resource}")

        # 模拟使用共享资源需要1秒钟的时间
        time.sleep(1)
    finally:
        # 释放线程锁
        lock.release()


# 创建10个线程来更新共享资源
threads = []
for i in range(10):
    thread = threading.Thread(target=update_shared_resource, name=f"Thread-{i + 1}")
    threads.append(thread)
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

print("Final shared resource value:", shared_resource)
